package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.AliyunConfig;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Service
public class SmsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private RestTemplate restTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    public static final String REDIS_KEY_PREFIX = "CHECK_CODE_";

    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * 发送短信验证
     * @param mobile
     * @return
     */
    public Map<String,Object> sendCheckCode(String mobile){
        Map<String,Object> result = new HashMap<>(2);
        try {
        String redisKey = REDIS_KEY_PREFIX +mobile;
        String value = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotEmpty(value)){
            result.put("code",1);
            result.put("msg","上一次发送的验证码还未失效");
            return result;
        }

        //String code=this.sendSmsAliyun(mobile);
        String code = "123456";

        if (null==code){
            result.put("code",2);
            result.put("msg","发送短信验证码失败");
            return result;
        }
        //发送验证码成功
        result.put("code",3);
        result.put("mag","ok");

        //将验证码存储到redis这里设置成两分钟
        this.redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(2));
        return result;
    }catch (Exception e){
            LOGGER.error("发送验证码出错！"+mobile,e);
            result.put("code",4);
            result.put("msg","发送验证码出现异常");
            return result;
        }
    }

    public String sendSmsAliyun(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(
                this.aliyunConfig.getRegionId(),
                this.aliyunConfig.getAccessKeyId(),
                this.aliyunConfig.getAccessKeySecret()
        );

        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId",this.aliyunConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers",mobile);
        request.putQueryParameter("SignName",this.aliyunConfig.getSignName());
        request.putQueryParameter("TemplateCode",this.aliyunConfig.getTemplateCode());
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");


        try {
            CommonResponse response = client.getCommonResponse(request);
            if (StringUtils.contains(response.getData(), "\"Code\":\"OK\"")){
                return code;
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}
